package initialize

import (
	"context"
	"fmt"
	"log"
	"time"
	common "user_service/config"
	mlMongo "user_service/mongo"
)

func NewMongoDatabase() mlMongo.Client {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// MongoDB 连接字符串
	connStr := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=admin",
		common.Configs.DB.User,
		common.Configs.DB.Password,
		common.Configs.DB.Host,
		common.Configs.DB.Port,
		common.Configs.DB.Name)

	// 连接到 MongoDB
	clientN, err := mlMongo.NewClient(connStr)

	if err != nil {
		log.Fatal(err)
	}

	err = clientN.Ping(ctx)
	if err != nil {
		log.Fatal(err)
	}

	return clientN
}

func CloseMongoDBConnection(client mlMongo.Client) {
	if client == nil {
		return
	}

	err := client.Disconnect(context.TODO())
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Connection to MongoDB closed.")
}
